/*
 * @Author: guoyangf
 * @Date: 2020-05-29 11:08:19
 * @LastEditTime: 2020-09-21 14:56:27
 * @Description: 列表控件
 */
import { Component } from 'react';
import { base } from 'nc-lightapp-front';
import { tableAndCardListScrollLoad, thumbListScrollLoad } from 'src/erm/sscrppublic/common/utils/scrollLoad';
import './index.less';
import { setTable } from '../../../../utils/setComponentUsed';

const { NCDiv } = base;


class ListCtrl extends Component {
    constructor(props) {
        super(props);
        this.NCProps = window.__SSC_NCProps;
        setTable(this.NCProps, props.regTableTplArea);

        this.state = {
            showAllFieldCard: {} //展开全部字段的card
        }

        //this.oprVisibleBtnString = props.oprVisibleBtn && props.oprVisibleBtn.toString();
        this.areaAllBtns = [];
        this.setBtn();
    }

    componentDidMount() {
        thumbListScrollLoad(() => {
            this.props.listScrollCallback && this.props.listScrollCallback();
        });
    }

    getCardJSX = (cardData, cardTpl) => {
        return cardData && cardData.cardRows.map((card, index) => {

            let listRowRecord = cardData.listRows[index].values;
            //调用业务函数，根据行数据控制按钮可见性
            let visibleBtns = [];
            if (this.props.oprColBtnsVisibleCtrl) {
                visibleBtns = this.props.oprColBtnsVisibleCtrl(listRowRecord, this.areaAllBtns);
            } else {
                visibleBtns = this.areaAllBtns;
            }

            let approvestatus = card.values.approvestatus || {};
            let tradeType = card.values.pk_tradetype.display
            let remark = card.values.remark && card.values.remark.display;

            let currtypeDisplay = (card.values.pk_currtype && card.values.pk_currtype.display) || '';
            let amount = card.values.amount || { display: '', value: '' };

            let tpl = cardTpl[card.values.pk_group.value + ':' + card.tradetypecode] || cardTpl[card.tradetypecode] || []

            //自动化标记值的拼接
            let fieldIdItemArr = [];
            let { billno = {}, apply_org = {} } = card.values
            tradeType && fieldIdItemArr.push(tradeType);
            apply_org.display && fieldIdItemArr.push(apply_org.display);
            billno.value && fieldIdItemArr.push(billno.value);

            //为true 时，显示感叹号
            let sagaError = card.values.saga_status && card.values.saga_status.value === "1";

            return (
                <li>
                    <NCDiv
                        className='card-item  nc-theme-zrow-bgc nc-theme-area-split-bc'
                        style={{ height: this.state.showAllFieldCard[billno.value] ? 'auto' : '80px' }}
                        fieldid={`${fieldIdItemArr.join('_')}`} areaCode={NCDiv.config.ListItem}
                    >
                        <div className='card-item-data'>
                            <div className='title-area'>
                                <i className='detail-idx'>{index + 1}</i>
                                {sagaError &&
                                    <span
                                        className='error-flag iconfont icon icon-gantanhao'
                                        onClick={() => {
                                            this.props.sagaIconClickEvent && this.props.sagaIconClickEvent()
                                        }}
                                    >
                                    </span>
                                }
                                <span className='pk_tradetype nc-theme-common-font-c' fieldid="pk_tradetype">{tradeType}</span>
                                <span className='remark nc-theme-common-font-c' fieldid="remark" title={remark}>
                                    {remark}
                                </span>
                                <span
                                    className='amount'
                                    fieldid="amount"
                                    title={currtypeDisplay + amount.display}
                                >
                                    {currtypeDisplay}
                                    {amount.value}
                                </span>
                            </div>
                            <div className='content-area'>
                                {tpl.map((item) => {
                                    if (!item.visible) {
                                        return null;
                                    }
                                    let valueObj = card.values[item.attrcode];
                                    let value = valueObj ? valueObj.display || valueObj.value : null;
                                    if (this.props.cardFieldRender && this.props.cardFieldRender[item.attrcode]) {
                                        value = this.props.cardFieldRender[item.attrcode](value, listRowRecord, index);
                                    }
                                    return (
                                        <div className="field-wrap">
                                            <span className="label nc-theme-title-font-c">
                                                {item.label}：
                                        </span>
                                            <span className="value nc-theme-common-font-c" title={value}>
                                                {value}
                                            </span>
                                        </div>
                                    )
                                })}
                            </div>
                        </div>

                        <div fieldid="bill-status" className={approvestatus.className} style={{ width: '60px', height: '60px', backgroundSize: '100%', backgroundImage: `url(${approvestatus.bgUrl})` }}>
                            {approvestatus.txt}
                        </div>
                        <div className='card-item-btn-wrap'>
                            {visibleBtns.map((btn) => {
                                return (
                                    <span
                                        className="card-item-btn"
                                        onClick={() => {
                                            this.onButtonClick(btn.key, listRowRecord, index); //必须使用列表的行数据。card行数据不全
                                        }}
                                    >
                                        {btn.title}
                                    </span>
                                )
                            })}
                        </div>


                        <i
                            fieldid="open-all"
                            className={this.state.showAllFieldCard[billno.value] ? "card-open-all open-all--rotate" : "card-open-all"}
                            onClick={() => {
                                let showAllFieldCard = this.state.showAllFieldCard;
                                showAllFieldCard[billno.value] = !showAllFieldCard[billno.value]
                                this.setState({
                                    showAllFieldCard
                                })
                            }}
                        ></i>
                    </NCDiv>
                </li>
            )
        })
    }

    onButtonClick = async (key, record, index) => {
        key = key.replace('__ssc-cap-suffix', '');
        console.log('点击按钮的key', key);
        let btnEvent = this.props.oprBtnEvent;
        if (this.props.oprBtnEvent instanceof Promise) {
            btnEvent = await this.props.oprBtnEvent;
        }
        if (btnEvent && btnEvent[key]) {
            this.props.oprBtnBeforeEvent && this.props.oprBtnBeforeEvent(key, record, index);
            let isExecAfterEvent = btnEvent[key](key, record, index);
            if (isExecAfterEvent instanceof Promise) {
                isExecAfterEvent = await isExecAfterEvent;
            }
            isExecAfterEvent !== false && this.props.oprBtnAfterEvent && this.props.oprBtnAfterEvent(key, record);
        }
    }


    setBtn() {

        let tplButtons = this.NCProps.button.getButtons() || [];

        tplButtons.forEach((btn) => {
            //tplButtons提供的是全部按钮，需要判断按钮区域
            if (btn.area == this.props.oprBtnTplArea) {
                let newBtn = { ...btn }
                newBtn.key = newBtn.key.replace('__ssc-cap-suffix', '')
                this.areaAllBtns.push(newBtn)
            }
        })

        //设置table上扩展列按钮
        this.NCProps.table.setTableRender(this.props.regTableTplArea, "opr", (text, record, index) => {
            //由于createOprationButton不能根据按钮区域控制按钮可见性，导致与详情页按钮控制产生冲突。所以弃用此api。

            //调用业务函数，根据行数据控制按钮可见性
            let visibleBtns = [];

            if (this.props.oprColBtnsVisibleCtrl) {
                visibleBtns = this.props.oprColBtnsVisibleCtrl(record, this.areaAllBtns);
            } else {
                visibleBtns = this.areaAllBtns;
            }

            return (
                this.NCProps.button.createErrorButton({
                    record: record,
                    sucessCallBack: () => {
                        //由于createOprationButton不能根据按钮区域控制按钮可见性，导致与详情页按钮控制产生冲突。所以采用冗余设置的方式来规避。
                        let keys = visibleBtns.map((btn) => { return `${btn.key}__ssc-cap-suffix` })
                        return this.NCProps.button.createOprationButton(keys, {
                            area: this.props.oprBtnTplArea,
                            buttonLimit: 3,
                            onButtonClick: (props, btnKey) => {
                                this.onButtonClick(btnKey, record, index);
                            }
                        });
                        /* return (
                            <div className='list-item-btn-wrap'>
                                {visibleBtns.map((btn) => {
                                    return (
                                        <span
                                            className="list-item-btn"
                                            onClick={() => {
                                                this.onButtonClick(btn.key, record, index);
                                            }}
                                        >
                                            {btn.title}
                                        </span>
                                    )
                                })}
                            </div>
                        ) */
                    }
                })
            )
        })
    }


    componentWillReceiveProps(nextProps) {

        if (nextProps.isShow && !this.props.isShow) {
            this.NCProps.table.updateTableHeight();

        }
        /* if (this.props.isShowDetailPage && !nextProps.isShowDetailPage ) { //从详情页切回列表页是，需要重置按钮状态。因为详情页可能对按钮状态进行了控制
            this.setBtn();
        } */
    }

    componentDidUpdate(prevProps) {
        if (prevProps.rowData != this.props.rowData) {
            this.NCProps.table.setAllTableData(this.props.regTableTplArea, this.props.rowData);
        }
    }

    render() {
        const { button, table, socket } = this.NCProps;
        const { createSimpleTable } = table;
        return (
            <div
                className='table-ctrl-wrap'
                style={{ display: this.props.isShow ? 'block' : 'none' }}
            >
                <div
                    style={{ display: this.props.showCardList ? 'none' : 'block' }}
                >
                    {this.props.showCardList ?
                        null
                        :
                        (
                            createSimpleTable(this.props.regTableTplArea, {
                                dataSource: this.props.regTableTplArea,
                                pkname: 'pk_task',
                                lazyload: true,
                                showIndex: true,
                                showCheck: this.props.showCheck,
                                onRowDoubleClick: (record, index) => {
                                    this.props.onRowDoubleClick && this.props.onRowDoubleClick(record, index);
                                },
                                onSelected: (...param) => {
                                    this.props.tableCheckboxOnSelect && this.props.tableCheckboxOnSelect();
                                },
                                onSelectedAll: (...param) => {
                                    this.props.tableCheckboxOnSelect && this.props.tableCheckboxOnSelect();
                                },
                                sort: {
                                    mode: 'single',
                                    backSource: true,
                                    sortFun: (sortParam) => {
                                        this.props.sortCallback && this.props.sortCallback(sortParam);
                                    }
                                },
                                alloweFilter: false, //禁用筛选
                                handlePageInfoChange: (props, config, pks, totalEles) => { //翻页器翻页

                                    this.props.paginationClickEvent && this.props.paginationClickEvent(this.props.regTableTplArea, pks);

                                },
                            })
                        )
                    }
                </div>
                <NCDiv
                    className='card-list-wrap ssc-row-thumb-scroll-mark nc-theme-gray-area-bgc nc-theme-area-split-bc'
                    style={{ display: this.props.showCardList ? 'block' : 'none' }}
                    fieldid={`card-list`} areaCode={NCDiv.config.ListItem}
                >
                    {
                        this.props.cardData.cardRows.length && this.props.showCardList ?
                            (
                                <ul>
                                    {this.getCardJSX(this.props.cardData, this.props.cardTpl)}
                                </ul>
                            )
                            :
                            (
                                <div className="card-no-data-wrap">
                                    <i className='no-data'></i>
                                    暂无数据
                                </div>
                            )

                    }



                </NCDiv >
            </div>
        )
    }
}

export default ListCtrl;